#include "sessionfriendarea.h"
#include "debug.h"
#include "Model/data.h"
#include <QScrollBar>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QStyleOption>
#include <QPainter>

using namespace model;
SessionFriendArea::SessionFriendArea(QWidget *parent):QScrollArea(parent)
{
    //1.设置滚动条
    this->setWidgetResizable(true);

    //设置滚动条及其样式
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(46, 46, 46);}");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    this->setStyleSheet("QWidget { border: none;}");//边框

    //2.创建widget出来
    container = new QWidget();
    container->setFixedWidth(280);
    this->setWidget(container);

    // 3. 给这个 widget 指定布局管理器, 以便后续添加元素进去
    QVBoxLayout *layout = new QVBoxLayout();
    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    container->setLayout(layout);

    // 简单测试一下滚动的效果 (没有问题), 先去掉, 后续添加 Item
    // for (int i = 0; i < 50; ++i) {
    //     QPushButton* btn = new QPushButton();
    //     btn->setText("按钮");
    //     layout->addWidget(btn);
    // }

// 构造出一些临时数据, 用来作为 "界面调试" 依据. 后续要删除掉
#if TEST_UI
    QIcon icon(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 30; ++i) {
        this->addItem(APPLYITEM,QString::number(i),icon, "张三" + QString::number(i), "最后一条消息" + QString::number(i));
    }
#endif
}

void SessionFriendArea::addItem(ItemType itemType, const QString& id, const QIcon &avatar, const QString &name, const QString &text)
{
    SessionFriendItem* item = nullptr;
    if (itemType == SESSIONITEM) {
        item = new SessionItem(this, id, avatar, name, text);
    } else if (itemType == FRIENDITEM) {
        item = new FriendItem(this, id, avatar, name, text);
    } else if (itemType == APPLYITEM) {
        item = new ApplyItem(this, id, avatar, name);
    } else {
        LOG() << "错误的 ItemType! itemType=" << itemType;
        return;
    }
    container->layout()->addWidget(item);
}

void SessionFriendArea::clear()
{
    QLayout *layout = container->layout();

    for(int i=0;i<layout->count();i++)
    {
        QLayoutItem *item = layout->takeAt(0);//只是移除
        if(item->widget())
        {
            delete item->widget();
        }
    }
}

void SessionFriendArea::clickItem(int index)
{
    // if(index < 0 || index >= this->children().count())
    //     return;

    if(index < 0 || index >= container->layout()->count())
    {
        LOG()<<"点击元素下标超出范围！index ="<<index;
        return;
    }
    QLayoutItem* layoutItem = container->layout()->itemAt(index);
    if (layoutItem == nullptr || layoutItem->widget() == nullptr) {
        LOG() << "指定的元素不存在! index=" << index;
        return;
    }
    SessionFriendItem* item = dynamic_cast<SessionFriendItem*>(layoutItem->widget());
    item->select();
}



SessionFriendItem::SessionFriendItem(QWidget *owner, const QIcon &heads, const QString &name, const QString &text)
    :owner(owner)
{
    //设置Item
    this->setFixedHeight(70);
    this->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");

    //创建网格布局管理器
    QGridLayout *layout = new QGridLayout();
    //调整
    layout->setContentsMargins(20, 0, 0, 0);
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);
    this->setLayout(layout);

    //创建头像
    QPushButton *headsBtn = new QPushButton();
    headsBtn->setFixedSize(50,50);
    headsBtn->setIconSize(QSize(50,50) );
    headsBtn->setIcon(heads);
    headsBtn->setStyleSheet("QPushButton {border: none;}");
    headsBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);


    //创建名字
    QLabel *nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel { font-size: 18px; font-weight: 600; }");
    nameLabel->setFixedHeight(35);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    //创建消息预览
    // QLabel *messageLabel = new QLabel();
    messageLabel = new QLabel();
    messageLabel->setText(text);
    messageLabel->setFixedHeight(35);
    messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 头像处于 0, 0 位置, 占据 2 行, 占据 2 列
    layout->addWidget(headsBtn, 0, 0, 2, 2);
    // 名字处于 0, 2 位置, 占据 1 行, 占据 1 列
    layout->addWidget(nameLabel, 0, 2, 1, 8);
    // 消息预览处于 1, 2 位置, 占据 1 行, 占据 1 列
    layout->addWidget(messageLabel, 1, 2, 1, 8);
}

void SessionFriendItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void SessionFriendItem::mousePressEvent(QMouseEvent *event)
{

    // this->setStyleSheet("QWidget { background-color: rgb(210, 210, 210);}");

    this->select();


}

void SessionFriendItem::enterEvent(QEnterEvent *event)
{
    if(this->selected)
        return;
    this->setStyleSheet("QWidget{background-color: rgb(220, 220, 220);}");
}

void SessionFriendItem::leaveEvent(QEvent *event)
{
    if(this->selected)
        return;
    this->setStyleSheet("QWidget{background-color: rgb(231, 231, 231);}");
}

void SessionFriendItem::select()
{
    //父亲窗口的孩子，不就是你和你的兄弟
    const QObjectList children = this->parentWidget()->children();

    //
    for (QObject* child : children) {
        if (!child->isWidgetType()) {
            // 判定是否是 widget.
            continue;
        }
        // 确实是 widget, 就把这里的child 强转成 SessionFriendItem
        SessionFriendItem* item = dynamic_cast<SessionFriendItem*>(child);
        if (item->selected) {
            item->selected = false;
            item->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");
        }
    }

    // 点击时, 修改背景色.
    // 此处不仅仅要设置当前 item 背景色, 也要还原其他元素的背景色.
    this->setStyleSheet("QWidget { background-color: rgb(210, 210, 210); }");
    this->selected = true;
}

SessionItem::SessionItem(QWidget *owner, const QString &id, const QIcon &heads, const QString &name, const QString &text)
    :SessionFriendItem(owner,heads,name,text),chatSessionId(id)
{

}

FriendItem::FriendItem(QWidget *onwer, const QString &id, const QIcon &heads, const QString &name, const QString &description)
    :SessionFriendItem(onwer,heads,name,description),userId(id)
{

}

ApplyItem::ApplyItem(QWidget *onwer, const QString &id, const QIcon &heads, const QString &name)
    :SessionFriendItem(onwer,heads,name,""),userId(id)
{
    // 1. 移除父类的 messageLabel
    QGridLayout* layout = dynamic_cast<QGridLayout*>(this->layout());
    layout->removeWidget(messageLabel);
    // 要记得释放内存, 否则会内存泄露.
    delete messageLabel;

    // 2. 创建两个按钮出来
    QPushButton* acceptBtn = new QPushButton();
    acceptBtn->setText("同意");
    QPushButton* rejectBtn = new QPushButton();
    rejectBtn->setText("拒绝");

    // 3. 添加到布局管理器中
    layout->addWidget(acceptBtn, 1, 2, 1, 1);
    layout->addWidget(rejectBtn, 1, 3, 1, 1);
}
